package db_gorm

import (
	"gitee.com/lipore/plume/errors"
	"gitee.com/lipore/plume/logger"
	"gitee.com/lipore/plume/trx"
	"gorm.io/driver/mysql"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type ID int64

var (
	DB *gorm.DB
)

func Connect(options ...Options) (trx.Manager, error) {
	conn, err := NewClient(options...)
	if err != nil {
		err = errors.WithCode(err, 0, "connect to default database failed")
		logger.Errorf("%v", err)
		return nil, err
	}
	DB = conn
	txManager := NewTxManager(conn)
	return txManager, nil
}

func dialect(dbType DBType, dsn string) gorm.Dialector {
	switch dbType {
	case Mysql:
		return mysql.Open(dsn)
	case Postgres:
		return postgres.Open(dsn)
	case SQLite:
		return sqlite.Open(dsn)
	default:
		return nil
	}
}

func NewClient(opts ...Options) (*gorm.DB, error) {
	config := NewConfig(opts...)

	logLevel := logger.WARN
	if config.ShowSql {
		logLevel = logger.INFO
	}
	l := NewLogger(&LoggerOptions{
		SlowThreshold:             config.SlowThreshold,
		LogLevel:                  logLevel,
		IgnoreRecordNotFoundError: true,
	})
	conn, err := gorm.Open(dialect(config.DBType, config.Dsn), &gorm.Config{
		Logger:         l,
		TranslateError: true,
	})
	if err != nil {
		return nil, err
	}
	return conn, nil
}
